package org.jeecg.modules.asset.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.asset.entity.AssetSetting;
import org.jeecg.modules.asset.service.IAssetSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 系统设置
 * @Author: jeecg-boot
 * @Date:   2025-11-16
 * @Version: V1.0
 */
@Api(tags="系统设置")
@RestController
@RequestMapping("/asset/assetSetting")
@Slf4j
public class AssetSettingController extends JeecgController<AssetSetting, IAssetSettingService> {
	@Autowired
	private IAssetSettingService assetSettingService;


	 @Value("${backup.host}")
	 private String host;
	 @Value("${backup.port}")
	 private String port;
	 @Value("${backup.username}")
	 private String username;
	 @Value("${backup.password}")
	 private String password;
	 @Value("${backup.database}")
	 private String database;
	 @Value("${backup.backupPath}")
	 private String backupPath;
	 @Value("${backup.mysqldumpPath}")
	 private String mysqldumpPath;
	
	/**
	 * 分页列表查询
	 *
	 * @param assetSetting
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "系统设置-分页列表查询")
	@ApiOperation(value="系统设置-分页列表查询", notes="系统设置-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AssetSetting>> queryPageList(AssetSetting assetSetting,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AssetSetting> queryWrapper = QueryGenerator.initQueryWrapper(assetSetting, req.getParameterMap());
		Page<AssetSetting> page = new Page<AssetSetting>(pageNo, pageSize);
		IPage<AssetSetting> pageList = assetSettingService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param assetSetting
	 * @return
	 */
	@AutoLog(value = "系统设置-添加")
	@ApiOperation(value="系统设置-添加", notes="系统设置-添加")
	//@RequiresPermissions("org.jeecg.modules:asset_setting:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody AssetSetting assetSetting) {
		assetSettingService.save(assetSetting);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param assetSetting
	 * @return
	 */
	@AutoLog(value = "系统设置-编辑")
	@ApiOperation(value="系统设置-编辑", notes="系统设置-编辑")
	//@RequiresPermissions("org.jeecg.modules:asset_setting:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody AssetSetting assetSetting) {
		assetSettingService.updateById(assetSetting);
		return Result.OK("保存成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "系统设置-通过id删除")
	@ApiOperation(value="系统设置-通过id删除", notes="系统设置-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:asset_setting:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		assetSettingService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "系统设置-批量删除")
	@ApiOperation(value="系统设置-批量删除", notes="系统设置-批量删除")
	//@RequiresPermissions("org.jeecg.modules:asset_setting:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.assetSettingService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "系统设置-通过id查询")
	@ApiOperation(value="系统设置-通过id查询", notes="系统设置-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AssetSetting> queryById(@RequestParam(name="id",required=true) String id) {
		AssetSetting assetSetting = assetSettingService.getById(id);
		if(assetSetting==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(assetSetting);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param assetSetting
    */
    //@RequiresPermissions("org.jeecg.modules:asset_setting:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AssetSetting assetSetting) {
        return super.exportXls(request, assetSetting, AssetSetting.class, "系统设置");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("asset_setting:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AssetSetting.class);
    }





	 @PostMapping(value = "/backupDatabase")
	 public Result<String> backup() {
		 int port2 = Integer.parseInt(port);
		 boolean b = backupMySQL(host, port2, username, password, database, backupPath);
		 if (!b) {
			 return Result.error("数据库备份失败");
		 }
		 return Result.OK("数据库备份成功!");
	 }


	private boolean backupMySQL(
			String host, int port, String username, String password,
			String database, String backupDir) {

		String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String backupFileName = database + "_" + timestamp + ".sql";
		File backupFile = new File(backupDir, backupFileName);

		// 确保备份目录存在
		if (!backupFile.getParentFile().exists()) {
			backupFile.getParentFile().mkdirs();
		}

		File mysqldumpFile = new File(mysqldumpPath);

		if (!mysqldumpFile.exists()) {
			log.error("mysqldump不存在于指定路径: " + mysqldumpPath);
			return false;
		}

		try {
			// 构建命令
			List<String> command = new ArrayList<>();
			command.add("cmd");
			command.add("/c");
			command.add("\"" + mysqldumpPath + "\"");  // 使用引号包裹路径，防止空格问题

			command.add("-h" + host);
			command.add("-P" + String.valueOf(port));
			command.add("-u" + username);
			command.add("-p" + password);
			command.add(database);

			ProcessBuilder processBuilder = new ProcessBuilder(command);
			processBuilder.redirectOutput(backupFile);

			Process process = processBuilder.start();

			// 读取错误信息
			BufferedReader errorReader = new BufferedReader(
					new InputStreamReader(process.getErrorStream()));

			StringBuilder errorMsg = new StringBuilder();
			String errorLine;
			while ((errorLine = errorReader.readLine()) != null) {
				errorMsg.append(errorLine).append("\n");
			}

			int exitCode = process.waitFor();
			if (exitCode == 0) {
				log.info("MySQL备份成功: " + backupFile.getAbsolutePath());
				return true;
			} else {
				log.error("备份失败，退出码：" + exitCode);
				log.error("错误信息：" + errorMsg.toString());
				if (backupFile.exists()) backupFile.delete();
				return false;
			}

		} catch (Exception e) {
			log.error("备份过程异常: " + e.getMessage());
			return false;
		}
	}
}
